package com.ror.java.se.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//使用Lock接口

public class Demo09 {
    public static void main(String[] args) {
        TicketConductor tc = new TicketConductor();
        Thread t1 = new Thread(tc, "窗口1");
        Thread t2 = new Thread(tc, "窗口2");
        Thread t3 = new Thread(tc, "窗口3");
        t1.start();
        t2.start();
        t3.start();
    }

    private static class TicketConductor implements Runnable {
        static int ticket = 0;
        static final Lock lock = new ReentrantLock();

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(10);
                    lock.lock(); //上锁
                    if (ticket >= 100) break;
                    ticket++;
                    System.out.println(Thread.currentThread().getName() + "卖出了第" + ticket + "张票！");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock(); //解锁
                }
            }
        }
    }
}
